package Model;

import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Map;

public class Data {

	private final byte[] NO_DATA_PULL = {1};
	
	// eager initialization is both thread safe and will also load the data from db
	private static volatile Data instance = new Data();
	
	private Map<ByteBuffer, Messages> m_Data;	

	private Data()
	{
		m_Data = new HashMap<ByteBuffer, Messages>();
	}
	
	public static Data getInstance()
	{
		return instance;
	}
	
	public byte[] pull(byte[] id) 
	{
		Messages msgs = m_Data.get(ByteBuffer.wrap(id));
		
		if (msgs  == null || msgs.size() == 0)
		{
			return NO_DATA_PULL;
		}
				
		return msgs.pop();
	}

	public void add(byte[] payload, byte[] key) 
	{
		if (payload == null || payload.length <= 1)
			return;
		
		ByteBuffer tokenWrapper = ByteBuffer.wrap(key);
		Messages msgs = m_Data.get(tokenWrapper);
		
		if (msgs == null)
		{
			msgs = new Messages();
			m_Data.put(tokenWrapper, msgs);
		}
				
		msgs.push(payload);
	}
}
